const express = require('express')
const compression = require('compression')
const bodyParser = require('body-parser')
const compose = require('compose-middleware').compose
const cors = require('cors')
module.exports = ({
  config,
  filterMiddleware,
  parseIntMiddleware,
  containerMiddleware,
  errorHandle,
  jwt,
  loginUser,
}) => {
  const router = express.Router()
  router.use(
    cors({
      // methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
      preflightContinue: false,
      // optionsSuccessStatus: 204,
      //  https://blog.csdn.net/chjj0904/article/details/90268813
      credentials: true,
      allowedHeaders:
        'Accept,Authorization,DNT,Content-Type,Referer,User-Agent',
      maxAge: 300,
    })
  )
  router.use(filterMiddleware).use(parseIntMiddleware)

  const auth = jwt.authenticate()
  const all = compose([auth, loginUser])
  const mids = { auth, all, loginUser }

  const apiRouter = express.Router()
  apiRouter.use(bodyParser.json()).use(containerMiddleware).use(compression())
  apiRouter.use('/auth', require('./modules/auth')(mids))
  apiRouter.use('/users', require('./modules/user')(mids))
  apiRouter.use('/menu', require('./modules/menu')(mids))
  apiRouter.use('/system', require('./modules/system')(mids))
  apiRouter.use('/role', require('./modules/role')(mids))

  router.use(config.get('apiPrefix'), apiRouter).use(errorHandle)

  return router
}
